from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. import models
from django.core.urlresolvers import reverse


def catesadd(request):
    if request.method == 'GET':
        #获取所有的商品分类
        data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        #分配数据
        context = {'cateslist':data}
        #加载模板
        return render(request,'myadmin/cates/add.html',context)
    elif request.method == 'POST':
        try:
            #执行添加
            ob = models.Cates()
            ob.name = request.POST.get('name')
            ob.pid = request.POST.get('pid')
            #判断是否为顶级分类
            if ob.pid == '0':
                ob.path = '0,'
            else:
                #获取当前所选的分类path
                fob = models.Cates.objects.get(id=ob.pid)
                ob.path = fob.path+ob.pid+','
            ob.save()
            return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cates_index')+'"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_cates_add')+'"</script>')

            

def catesindex(request):
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    
    context = {'cateslist':data}

    return render(request,'myadmin/cates/index.html',context)

def catesdel(request):
    #分类id
    cid = request.GET.get('cid')

    #判断当前类下是否还有子类
    num = models.Cates.objects.filter(pid=cid).count()
    if num:
        #有子类不能删除
        return JsonResponse({'error':1,'msg':'当前类下有子类,不能删除'})

    #再确认当前类下是否有商品发布

    #获取分类对象
    ob = models.Cates.objects.get(id=cid)
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功'})


#分类的修改
def catesedit(request):
    try:
        #根据cid获取分类对象
        ob = models.Cates.objects.get(id=request.GET.get('cid'))
        ob.name = request.GET.get('name')
        ob.save()
        return JsonResponse({'error':0,'msg':'更新成功'})
    except:
        return JsonResponse({'error':1,'msg':'更新失败'})
